package net.sevear.chaos.recommend
{
	import com.adobe.serialization.json.JSON;
	import com.douban.auth.DBAuthenticate;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.utils.Timer;
	
	import net.sevear.chaos.download.Predef;
	import net.sevear.chaos.event.RecommendEvent;
	import net.sevear.chaos.vo.UserInfo;
	
	public class RecommendStatInfoUpdater extends EventDispatcher
	{
		public static const EVENT_ERR:String = "Error happend when getting recommend statistics";
		public static const ALL_ITEMS_UPDATED:String = "All the items updated";
		
		private var _source:Array;
		private var _timer:Timer;
		private var iterator:int;
		private var loader:URLLoader;
		private var rst:URLRequest;
		public function RecommendStatInfoUpdater(arr:Array)
		{
			super(null);
			loader = new URLLoader();
			loader.addEventListener(IOErrorEvent.IO_ERROR,onIOErr);
			loader.addEventListener(Event.COMPLETE,onLoaderComplete);
			this._source = arr;
			rst = new URLRequest(encodeURI(Predef.CHAOS_HOST+
				RecommendManager.RECOMMEND_URL));
//			rst.idleTimeout = 10000;
			
		}
		
		public function startUpdate():void{
			iterator = 1;
			try{
				loader.close();
			}catch(e:Error){
				
			}
			if(_source!=null && _source.length>0){
				initTimer();
				processList();
			}
		}
		
		public function stopUpate():void{
			if(_timer!=null && _timer.running == true){
				_timer.stop();
				_timer = null;
			}
			this._source = null;
		}
		
		private function initTimer():void{
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER,onTimer);
		}
		
		private function processList():void{
			var vars:URLVariables = new URLVariables();
			vars.uid= DBAuthenticate.getInstance().dbUID;
			vars.op = "stat";
			var userInfo:UserInfo = _source[iterator-1] as UserInfo;
			vars.cpid = userInfo.dbID;
			rst.data = vars;
			loader.load(rst);
		}
		
		//TODO:
		private function onTimer(e:TimerEvent):void{
			
		}
		
		private function onIOErr(e:IOErrorEvent):void{
			iterator++;
			if(iterator>_source.length){
				dispatchEvent(new Event(ALL_ITEMS_UPDATED));
				if(_timer.running){
					_timer.stop();
				}
			}else{
				processList();
			}
		}
		
		private function onLoaderComplete(e:Event):void{
			var rstStr:String = (e.currentTarget as URLLoader).data as String;
			var rst:Object = JSON.decode(rstStr);
			dispatchEvent(new RecommendEvent(RecommendEvent.GET_RECOMMEND_STATICS,rst));
			iterator++;
			if(iterator>_source.length){
				dispatchEvent(new Event(ALL_ITEMS_UPDATED));
				if(_timer.running){
					_timer.stop();
				}
			}else{
				processList();
			}
		}
	}
}